package com.rock.dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class SelectDom {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {

        //建立DocumentBuilderFactory,用于获得DocumentBuilder对象：
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //建立DocumentBuilder
        DocumentBuilder documentBuilder = factory.newDocumentBuilder();
        //建立Document对象  获取树的入口
        Document doc = documentBuilder.parse("D:\\code\\homework\\Monday\\src\\resource\\office.xml");
        //建立NodeList
        NodeList node = doc.getElementsByTagName("office");
        //遍历xml获取办公室信息
        for (int i = 0; i < node.getLength(); i++) {
            //创建Element对象
            Element element = (Element) node.item(i);
            String name = element.getElementsByTagName("name").item(0).getFirstChild().getNodeValue();
            String addr = element.getElementsByTagName("addr").item(0).getFirstChild().getNodeValue();
            String area = element.getElementsByTagName("area").item(0).getFirstChild().getNodeValue();
            System.out.println("办公室名字: "+name + "  " + "地址: "+addr + "  "+"面积: "+area);
        }
    }
}
